﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using PServiceBus.Core.Runtime.Transports;
using PServiceBus.Ftp;
using System.Runtime.Serialization;
using System.ComponentModel.Composition;
using PServiceBus.Core.Runtime.Messages;
using PServiceBus.Core.Provider;
using PServiceBus.Core.Runtime.Extensions;

namespace PServiceBus.Transports {
    [Serializable]
    [DataContract]
    [Export(typeof(ITransport))]
    public class FtpTransport : ITransport {

        [DataMember]
        public string Url { get; set; }

        [DataMember]
        public string UserName { get; set; }

        [DataMember]
        public string Password { get; set; }

        [DataMember]
        public string AliasToAddToFileName { get; set; }

        [DataMember]
        public string FileExtension { get; set; }

        [DataMember]
        public string FileNameTemplate { get; set; }

        [DataMember]
        public string FolderName { get; set; }

        #region ITransport Members
        [DataMember]
        public TransportFormat Format { get; set; }

        public TransportResponse Send(string message, Dictionary<string, object> messageStructure) {
            var tranResponse = TransportResponse.New<FtpTransport>();
            try {
                var format = TransportProvider.GetMessageFormat(message);
                FolderName = FolderName ?? string.Empty;
                FolderName = FolderName.Replace("\\", "/");
                FolderName = !String.IsNullOrWhiteSpace(FolderName) ? 
                    (FolderName + (FolderName.EndsWith("/") ? string.Empty : "/" )) : FolderName;
                AliasToAddToFileName = AliasToAddToFileName ?? string.Empty;
                FileExtension = FileExtension ?? ".txt";
                FileExtension = (FileExtension.StartsWith(".") ? string.Empty : ".") + FileExtension;
                var messageMapper = MessageMapper.Map(message, messageStructure);
                foreach (var msg in messageMapper.Tokens) StoreFile(msg, format);
                tranResponse.Success = true;
            }
            catch (Exception ex) {
                tranResponse.Message = ex.ToString();
            }
            return tranResponse;
        }

        public void StoreFile(MessageMapperToken message, TransportFormat format) {
            var filename = (FileNameTemplate != null ? message.TransformTemplate(FileNameTemplate) : null) ?? Guid.NewGuid().ToString();
            var destFile = String.Format("{0}{1}{2}{3}", FolderName, filename, AliasToAddToFileName, FileExtension);
            var provider = new Ftp.Provider(Url, UserName, Password);
            provider.Upload(message.ToString(format), destFile);
        }
        #endregion
    }
}
